<?php
namespace app\backend\controller;

class Banner extends Backend {
	
	public function index() {
		
		$view = \think\View::instance();
		$request = \think\Request::instance();
		
		$where = array();
		$where['is_del'] = 0;
		$condition = array();
		$condition['title'] = $request->get('title', '');
		if(0 < mb_strlen($condition['title'], 'utf8')){
			$where['banner.title'] = array('like', '%%'.$condition['title'].'%%');
		};
		$view->assign('condition', $condition);
		
		$field = array(
			'banner.*',
		);
		$banner_select = \app\common\model\BannerModel::field($field)
			->where($where)->order('banner.id DESC')->paginate(10, false, array('query'=>$condition));
		$view->assign('page', $banner_select->render());
		
		$subscriber_list = array();
		foreach($banner_select as $BannerModel){
			$subscriber_list[] = $BannerModel->toArray();
		};
		$view->assign('data_list', $subscriber_list);
		
		unset($where, $condition, $field, $banner_select, $BannerModel);
		return $view->fetch();
		
	}
	
	public function create() {
		
		$request = \think\Request::instance();
		if($request->isAjax()){
			
			$parameter = \think\Request::instance()->post();
			$judge_1 = array_key_exists('title', $parameter) && is_string($parameter['title']) && (0 < mb_strlen($parameter['title'], 'utf8'));
			$judge_2 = array_key_exists('image', $parameter) && is_string($parameter['image']) && (0 < mb_strlen($parameter['image'], 'utf8'));
			if(!$judge_1 || !$judge_2){
				return $this->disposeJson(1, '参数校验失败');
			};
			
			$time = time();
			$BannerModel = new \app\common\model\BannerModel();
			$BannerModel->title = $parameter['title'];
			$BannerModel->img_url = $parameter['image'];
			$BannerModel->create_time = $time;
			$BannerModel->is_disable = 0;
			$BannerModel->is_del = 0;
			$result = $BannerModel->save();
			if(false == $BannerModel){
				return $this->disposeJson(1, '保存数据失败');
			};
			
			return $this->disposeJson(0, '操作成功，即将跳转');
			
		}else{
			
			$view = \think\View::instance();
			
			$view->assign('banner', \think\Config::get('upload_image.banner'));
			
			return $view->fetch();
		};
		
	}
	
	public function del() {
		
		$parameter = \think\Request::instance()->post();
		$judge_1 = array_key_exists('id', $parameter) && is_integer($parameter['id']) && (0 < $parameter['id']);
		if(!$judge_1){
			return $this->disposeJson(1, '参数校验失败');
		};
		
		$BannerModel = \app\common\model\BannerModel::get($parameter['id']);
		if((null === $BannerModel) || (1 === $BannerModel->getData('is_del'))){
			return $this->disposeJson(1, '目标不存在，请刷新后重试');
		};
		
		$BannerModel->is_del = 1;
		$result = $BannerModel->save();
		if(false == $result){
			return $this->disposeJson(1, '删除目标失败，请刷新后重试');
		};
		
		return $this->disposeJson(0, '操作成功，即将跳转');
	}
	
}